package dbadapters;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import entities.Employee;

/**
 * used for adding new employees to the db
 * 
 * @author eks691
 */
public class AddEmployeeDB {

	/**
	 * adds a employee and affiliated info to the db
	 * 
	 * @param myEmployee
	 *            employee to be added to db
	 * @precond all info for myEmployees is filled in
	 * @precond employee has not already been placed in db
	 */
	public AddEmployeeDB(Employee myEmployee) {
		try {
			Class.forName("org.postgresql.Driver");
		} catch (ClassNotFoundException cnfe) {
			System.out.println("Couldn't find driver class:");
			cnfe.printStackTrace();
		}

		Connection c = null;
		try {
			c = DriverManager.getConnection(
					"jdbc:postgresql://papyrus.usask.ca/cmpt370group00",
					"cmpt370group00", "an7x482d");
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			System.out.println(e);
		}

		Statement stmt = null;
		try {
			stmt = c.createStatement();
		} catch (SQLException e3) {
			// TODO Auto-generated catch block
			e3.printStackTrace();
		}

		// build the query used to insert the employee and related information
		String employeequery = "INSERT INTO employees VALUES (";
		employeequery += myEmployee.getID() + ", ";
		employeequery += "'" + myEmployee.getPassword() + "', ";
		employeequery += "'" + myEmployee.getName() + "', ";
		employeequery += "'" + myEmployee.getBirthdateAsString() + "', ";
		employeequery += "'" + myEmployee.getAddress() + "', ";
		employeequery += "'" + myEmployee.getPhoneNumber() + "', ";
		employeequery += "'" + myEmployee.getEmail() + "', ";

		// check if employee is in db already
		boolean isValid = true;
		ResultSet rs = null;
		try {
			rs = stmt.executeQuery("SELECT * FROM employees WHERE id="
					+ myEmployee.getID());
		} catch (SQLException e3) {
			// TODO Auto-generated catch block
			e3.printStackTrace();
		}
		try {
			if (rs.next()) {
				isValid = false;
			}
		} catch (SQLException e3) {
			// TODO Auto-generated catch block
			e3.printStackTrace();
		}

		// Cleanup
		try {
			rs.close();
		} catch (SQLException e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		}

		if (isValid) {
			try {
				stmt.execute(employeequery);
			} catch (SQLException e3) {
				// TODO Auto-generated catch block
				e3.printStackTrace();
			}
		}

		try {
			stmt.close();
		} catch (SQLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		try {
			c.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}